package edu.sjtu.grid.workflow.schedule;

import java.util.List;

import edu.sjtu.grid.workflow.facts.Facts;
import edu.sjtu.grid.workflow.facts.Job;
import edu.sjtu.grid.workflow.facts.Mapping;
import edu.sjtu.grid.workflow.iterator.UpwardRankIterator;

public class HeuristicSearchSchedule extends ScheduleBase{

	private UpwardRankIterator iterator = null;
	private double deadline = 0;
	
	public HeuristicSearchSchedule(Facts facts, double deadline) {
		super(facts, ScheduleType.HeuristicSearch);
		this.deadline = deadline;
		this.getRun().setDeadline(deadline);
	}
	
	public String toString()
	{
		return super.toString("deadline: " + deadline + "\n");
	}
	
	@Override
	protected void doSchedule()
	{
		//upward rank sorting & LFT(latest finished time)
		this.iterator = this.getFacts().getAdag().getUpwardRankIterator();
		
		//search
		this.setResult(doScheduleHelper());
	}
	
	private boolean doScheduleHelper()
	{
		if(this.reachMaxRunTime())
			return false;
		
		if(!this.iterator.hasNext())
			return true;
		
		Job job = (Job)this.iterator.next();
		List<Mapping> mappingList = this.getRun().getMappingList(job, this.deadline);
		for(Mapping map : mappingList)
		{	
			//confirm
			this.getRun().confirmMapping(map);
			
			if(doScheduleHelper())
				return true;
			
			//unconfirm
			this.getRun().removeMapping(map);
		}
		this.iterator.before();
		return false;
	}

}
